package com.itzhoun.aop;

import com.itzhoun.annotation.DecryptField;
import com.itzhoun.utils.DecryUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Objects;

/**
 * @author zhounan
 * @date 2024/02/03 17:56
 * @Description
 */

@Component
@Aspect
@Slf4j
public class DecryptAop {

    /**
     * 定义需要解密的切入点
     */
    @Pointcut(value = "@annotation(com.itzhoun.annotation.DataDecryption)")
    public void pointcut() {
    }

    /**
     * 命中的切入点时的环绕通知
     *
     * @param joinPoint 切点
     * @return
     * @throws Throwable
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("//环绕通知 start");
        Object[] args = joinPoint.getArgs();
        if (null == args || args.length == 0) {
            return joinPoint.proceed();
        }
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            DecryptField annotation = parameter.getAnnotation(DecryptField.class);
            Object arg = args[i];
            if (null != annotation) {
                args[i] = DecryUtils.aesDecryption(String.valueOf(arg));
            }else {
                handleDecrypt(arg);
            }
        }
        return joinPoint.proceed(args);
    }

    private void handleDecrypt(Object responseObj) throws Exception {
        if (Objects.isNull(responseObj)) {
            return;
        }
        Field[] fields = responseObj.getClass().getDeclaredFields();
        for (Field field : fields) {
            boolean hasSecureField = field.isAnnotationPresent(DecryptField.class);
            if (hasSecureField) {
                field.setAccessible(true);
                String encryptValue = (String) field.get(responseObj);
                String s = DecryUtils.aesDecryption(encryptValue);
                field.set(responseObj, s);
            }
        }
    }

}
